import React, { Component } from 'react'
import CardWrapper from '../../card-wrapper'
import MyEcahrt from '@/components/MyEcharts';
import EmptyData from '@/components/EmptyData';
import { Link } from 'react-router-dom';
import { Table, Select, Tooltip, Loading, Pagination ,Input} from '@knownsec/react-component';
import getPieOption from '../options/pie'
import getThrendOption from '../options/line'
import {getGroupList,getTrend} from '~/API'
import moment from 'moment';
import './index.less'
import { datetime } from '@/common/formatter';
import RuleTable from '@/components/RuleTable'
import CopyText from '@/components/copy'
import s from './index.less'
import { filterNull } from '@/utils';

const info=localStorage.info?JSON.parse(localStorage.info).modules:[]
class Accessibility extends Component {
  constructor(props) {
    super(props)
    this.state = {
      target_group_name:'',
      selectv: ['a'],
      dataList: [],
      normalNum: 0,
      anormalNum: 0,
      unknownNum:0,
      timeList: [],
      normalList: [],
      anormalList: [],
      loading: false,
      queryVal:{target_name:'',target_url:''},
      tableFilter: {
        page: 1,
        limit: 10
      },
      total: 0
    }
    // const [selectv, setSelect] = useState(['a']);
  }
  avaiText = (e = {}) => {
    if(e.cloud.hasOwnProperty('created_at')){
        return e.local.is_normal&&e.cloud.is_normal;
      }else{
        return e.local.is_normal;
      }
  };
  getDetailColumns = () => {
    let columns = [
      {
        title: '业务系统',
        dataIndex: 'target_url',
        render: (e, row) => {
          const name = row.target_name ? row.target_name : row.target_title;
          return (
            <Tooltip
              overlay={
                <>
                  <p>业务系统：<CopyText text={e}/></p>
                  <p>业务系统名称：{name || '暂未设置'}</p>
                </>
              }
              placement="topLeft"
            >
              <div>
                <Link className="hrefName" to="#" onClick={() => {
                  window.open(e);
                }}>
                  {e}
                </Link>
                <div
                  className="targetName"
                  style={{ color: name ? '#2A2B31' : '#ccc' }}
                  onClick={() => {
                    const random = Math.random();
                    this.changeName(row);
                  }}
                >
                  {name || '点击设置业务系统名称'}
                </div>
              </div>
            </Tooltip>
          );
        },
      },
      {
        title: '开始监测时间',
        dataIndex: 'started_at',
        key: 'started_at',
        render: (val) => (val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '-'),
      },
    //   {
    //     title: '累计响应正常',
    //     dataIndex: 'normal_total',
    //     key: 'normal_total',
    //     className: 'stablewidthsm',
    //     render: (val, data) =>
    //       data.availability?.normal_total || data.availability?.normal_total == 0
    //         ? data.availability.normal_total
    //         : '-',
    //   },
    //   {
    //     title: '累计响应异常',
    //     dataIndex: 'abnormal_total',
    //     key: 'abnormal_total',
    //     className: 'stablewidthsm',
    //     render: (val, data) =>
    //       data.availability?.abnormal_total || data.availability?.abnormal_total == 0
    //         ? data.availability.abnormal_total
    //         : '-',
    //   },
      {
        title: '最近监测时间',
        dataIndex: 'ended_at',
        key: 'ended_at',
         render: (value) => {
          const time = value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-';
          return (
            <Tooltip
              overlay={
                <>
                  <p>最近监测时间：{time}</p>
                </>
              }
              placement="topLeft"
            >
                <div>
                  {time}
                </div>
            </Tooltip>
          );
        },
      },
      {
        title: '预计下次监测时间',
        dataIndex: 'next_start_at',
        key: 'next_start_at',
         render: (value) => {
          const time = value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-';
          return (
            <Tooltip
              overlay={
                <>
                  <p>预计下次监测时间：{time}</p>
                </>
              }
              placement="topLeft"
            >
                <div>
                  {time}
                </div>
            </Tooltip>
          );
        },
      },
      {
        title: '最近监测状态',
        dataIndex: 'availability',
        key: 'availability',
        className: 'stablewidthsm',
        render: (e) => {
          const STATUS=['未知','响应正常','响应异常']
          const STATUS_C=['#7f7e7d','#11ab4e','#f04038']
        const {normal_status,local,cloud}=e

              if (!e.is_check) {
                return (
                  <Tooltip overlay={'未开启监测'} placement="topLeft">
                    <div className="siteInfo">
                      <span className="circular" style={{ background: '#9f958b' }}></span>
                      <div className="event-link event-high-color" style={{ color: '#7f7e7d' }}>
                        未知
                      </div>
                    </div>
                  </Tooltip>
                );
              }
          const tip = (
            <div>
              <div>
                <span>
                  本地&nbsp;{STATUS[local.normal_status]}
                  ({datetime(e.local.created_at)||'--'})
                </span>
              </div>
              <div>
                <span>
                云端&nbsp;{STATUS[cloud.normal_status]}(
                {datetime(e.cloud.created_at) || '--'})
                </span>
              </div>
            </div>
          );
          return (
            <Tooltip overlay={tip} placement="topLeft">
              <div>
                <div
                  className="event-link event-high-color"
                >
                  <span style={{ color:STATUS_C[normal_status]}}> {STATUS[normal_status]}</span>
                </div>
              </div>
            </Tooltip>
          );
        },
      },
      {
        title: '操作',
        dataIndex: 'option',
        key: 'option',
        className: 'stablewidthsm',
        render: (value, _data) => (
          <>
            <a href={`/#/dashboard?sid=${_data.task_session_id}&id=${_data.target_id}&type=availability&url=${_data.target_url}`} target='_blank' className="main-color">
                查看报表
            </a>
          </>
        ),
      },
    ];
    return columns
  }
  
  setSelect(val) {
    this.setState({
      selectv: val
    });
  }
  changeName(row) {
    var _this = this
    _this.props.change(row, _this.props.createForm, function(e){
      if(e){ _this.getScanList() }
    })
  };
  getScanList(){
    this.setState({loading: true})
    const {target_name,target_url}=this.state.queryVal
    const obj=target_name||target_url?{page:1,limit: 10,target_name, target_url}:this.state.tableFilter
    const data=filterNull(obj)
    getGroupList({type: 'availability', id: this.props.id, data}).then(res =>{
      this.setState({loading: false})
      if(res.status === 'success'){
        let normal = 0, anormal = 0,unknown=0
        res.data?.data.forEach(item => {
            normal += item.availability.normal_status=="1" ? 1 : 0
            anormal += item.availability.normal_status=="2"  ? 1 : 0
            unknown += item.availability.normal_status=="0"  ? 1 : 0
        })
        this.setState({dataList: res.data.data, tableFilter: { ...this.state.tableFilter, page: res.data.page }, total: res.data.total, normalNum: normal, anormalNum: anormal,unknownNum:unknown,target_group_name:res.data.target_group_name})
      }
    })
  }
  getTrendData(){
    const start = moment().add(-7, 'd').format('YYYY-MM-DD')
    const end = moment().format('YYYY-MM-DD')
    const data = {time_low: start,time_high: end}
    this.setState({loading: true})
    getTrend({type: 'availability', id: this.props.id, data: data}).then(res => {
      this.setState({loading: false})
      if(res.status === 'success'){
        let dateList = [], nList = [], anList =[]
        const data = res.data?.trend?.reverse() || []
        data.forEach(item => {
          dateList.push(moment(item.date).format('YYYY-MM-DD HH:mm:ss'))
          nList.push(item.normal_target)
          anList.push(item.abnormal_target)
        })
        this.setState({timeList: dateList, normalList: nList, anormalList: anList})
      }
    })
  }
  onSearchChange = (page) => {
    var _this = this;
    if (page&&page?.page) {
      _this.setState({tableFilter: { page:page.page, limit: page.limit }}, () =>_this.getScanList() );
    } else {
      _this.setState(
        {
          page: 1,
          limit: 10,
        },
        function () {
          _this.getScanList();
        }
      );
    }
  };
  componentDidMount(){
    this.getScanList()
    this.getTrendData()
  }
  render () {
    let detailColumns = this.getDetailColumns()
    let accessiableSiteData = [
      {
        name: '正常访问',
        value: this.state.normalNum,
        color: ['#11AB4E', '#48D796'],
      },
      {
        name: '异常访问',
        value: this.state.anormalNum,
        color: ['#FF4242', '#FF7777'],
      },
      {
        name: '未知',
        value: this.state.unknownNum,
        color: ['#7f7e7d', '#7f7e7d'],
      }
    ]
    let accessiableSiteOption = getPieOption(accessiableSiteData, true)

    let dates = this.state.timeList
    let data = [{ color: '#11AB4E', data: this.state.normalList, name: '全天可用性正常' },{ color: '#FF4242', data: this.state.anormalList, name: '可用性异常' }]
    let accessiableUnusualOption = getThrendOption({ dates, data })
    return <div className="tm-accessibility">
      <div className="condition">
        <label className="targetName">任务组名称：{this.state.target_group_name||'--'}</label>
        <label>更新时间：{moment(new Date()).format('YYYY-MM-DD HH:mm:ss')}</label>
      </div>
      <div className="state">
        <Loading show={this.state.loading} label="" />
        <CardWrapper title="当前网站可用性分布" className="accessiable-site">
          {accessiableSiteOption?<MyEcahrt option={accessiableSiteOption}></MyEcahrt>: <EmptyData size="small" />}
        </CardWrapper>
        <CardWrapper title="最近7天业务系统可用性数量变化趋势" className="accessiable-unusual">
          {this.state.timeList.length?(<MyEcahrt option={accessiableUnusualOption}></MyEcahrt>):(<EmptyData size="small"/>)}
        </CardWrapper>
      </div>
      <CardWrapper title="业务系统可用性监测列表" className="vul-site-list">
      <div className="searchTool">
          <Input
            pro
            placeholder="搜索业务系统名称"
            value={this.state.queryVal.target_name}
            search
            className={'search-button'}
            onSearch={(e) => {
              this.onSearchChange({ target_name: e.value });
            }}
            clear
            onChange={(value) => {
              this.setState({queryVal:{...this.state.queryVal,target_name:value.value}})
              if (!value.e) {
              this.onSearchChange();
                return;
              }
            }}
          ></Input>
          <Input
            pro
            placeholder="搜索业务系统地址"
            value={this.state.queryVal?.target_url}
            search
            className={'search-button'}
            onSearch={(e) => {
              this.onSearchChange({ target_url: e.value });
            }}
            clear
            onChange={(value) => {
              this.setState({queryVal:{...this.state.queryVal,target_url:value.value}})
              if (!value.e) {
              this.onSearchChange();
                return;
              }
            }}
          ></Input>
          </div>
        {(info.includes('cloud')||info.includes('availability'))? 
        <>
          <Table 
            columns={detailColumns} 
            className={s.table}
            tableLoading={this.state.loading}
            loadingLabel=""
            data={this.state.dataList}></Table>
          {this.state.total > 10 && <Pagination
            key={Number(123)}
            style={{textAlign: 'right', marginTop: '20px'}}
            current={this.state.tableFilter.page}
            showQuickJumper={{ goButton: true }}
            showSizeChanger={true}
            pageSize={this.state.tableFilter.limit}
            pageSizeOptions={['10', '20', '50']}
            total={this.state.total}
            showTotal={(total) => `共${total}条`}
            onChange={(page, size) => {
              this.onSearchChange({ page, limit: size });
            }}
          />}
        </>:
        <RuleTable columns={detailColumns} data={this.state.dataList}></RuleTable>
        }
      </CardWrapper>
    </div>
  }
}

export default Accessibility
